from utils.convert import (
    rj_imglist,
    add_ad_service,
    footer_placeholder,
    header_placeholder,
)

from bs4 import BeautifulSoup

img_list = [
    "https://bio-mercury-1316961827.cos.ap-guangzhou.myqcloud.com/photos/mce/mce_1.jpg",
    "https://bio-mercury-1316961827.cos.ap-guangzhou.myqcloud.com/photos/mce/mce_2.jpg",
    "https://bio-mercury-1316961827.cos.ap-guangzhou.myqcloud.com/photos/mce/mce_3.jpg",
    "https://bio-mercury-1316961827.cos.ap-guangzhou.myqcloud.com/photos/mce/mce_4.jpg",
    "https://bio-mercury-1316961827.cos.ap-guangzhou.myqcloud.com/photos/mce/mce_5.jpg",
]


def sku_generator(item: dict) -> list:
    """生成促销价sku - 65 折"""
    sku_list = []
    for _item in item["sku_list"]:
        sku_list.append(
            {
                "code": item["code"] + "-" + _item["spec"],
                "price": 0.65 * _item["price"],
                "directoryPrice": 1.9 * _item["price"],
                "stock": 999,
                "carryFeeTemplateId": "4611",
                "skuAttributes": [
                    {
                        "attributeName": "产品规格",
                        "attributeValue": _item["spec"],
                    }
                ],
                "deliveryTime": 1,
                "unit": "支",
            }
        )
    return sku_list


def gen_mce_ad() -> str:
    """生成 MCE 促销广告"""
    soup = BeautifulSoup("", "html.parser")
    ad_img = soup.new_tag(
        "img",
        attrs={
            "class": "cxsw_ad_img",
            "src": "https://bio-mercury-1316961827.cos.ap-guangzhou.myqcloud.com/photos/mce/mce_ad_img.png",
        },
    )
    return str(ad_img)


def gen_upload_dict(proinfo: dict) -> dict:
    """处理商品原始信息

    添加促销广告，计算促销价格
    """
    proinfo["desc"] = (
        add_ad_service()
        + header_placeholder()
        + gen_mce_ad()
        + proinfo["desc"]
        + footer_placeholder()
    )
    proinfo["skuInfos"] = sku_generator(proinfo)
    del proinfo["sku_list"]
    return proinfo


def raw_upload_dict(proinfo: dict) -> dict:
    """处理商品原始信息

    保存原始价格和商品详情
    """
    proinfo["photos"] = rj_imglist(mce_img_list)
    # 蛋白组学分类
    proinfo["categoryId"] = 231
    proinfo["brandId"] = 376
    proinfo["deliveryTime"] = 1
    proinfo["status"] = 3
    return proinfo


def process_des(html):
    """更新产品详情DOM

    Args:
        html (_type_): _description_

    Returns:
        _type_: _description_
    """
    content = html.replace('<img src=""/>\n', "")
    soup = BeautifulSoup(content, "html.parser")

    # 删除data:image 的img 标签
    img_tags = soup.find_all("img", src=lambda x: x and x.startswith("data:image"))
    if img_tags:
        for img_tag in img_tags:
            img_tag.decompose()

    # 删除旧版广告
    old_ad_tag = soup.find("div", attrs={"id": "con_header"})
    if old_ad_tag:
        old_ad_tag.decompose()

    div_dom = update_service_dom(soup)
    return str(div_dom)


def update_service_dom(soup):
    service_tags = soup.find_all("div", attrs={"class": "cxsw_service"})
    # 更新广告
    if service_tags:
        # 删除广告服务
        for service_tag in service_tags:
            service_tag.decompose()

        # 删除头部占位符
        header_tags = soup.find_all("div", attrs={"class": "cxsw_header_placeholder"})
        if header_tags:
            for header_tag in header_tags:
                header_tag.decompose()

        # 删除底部占位符
        footer_tags = soup.find_all("div", attrs={"class": "cxsw_footer_placeholder"})
        if footer_tags:
            for footer_tag in footer_tags:
                footer_tag.decompose()

    # 创建商品详情 dom
    description_tags = soup.find_all("div", attrs={"class": "cxsw_description"})
    if description_tags:
        return (
            add_ad_service() + header_placeholder() + str(soup) + footer_placeholder()
        )
    else:
        # 创建新 html
        _description = BeautifulSoup("", "html.parser")
        div_dom = _description.new_tag("div", attrs={"class": "cxsw_description"})

        div_dom.append(soup)
        return (
            add_ad_service()
            + header_placeholder()
            + str(div_dom)
            + footer_placeholder()
        )


def gen_upadte_data(pro: dict) -> dict:
    """生成更新数据"""
    pro["photos"] = rj_imglist(img_list)
    pro["desc"] = process_des(pro["desc"])

    for sku in pro["skuInfos"]:
        sku["directoryPrice"] = f"{sku['price'] * 1.9:.2f}"
        if sku["differentPrices"] == None:
            del sku["differentPrices"]
    return pro
